﻿using CK.Sprite.Form.Core;
using CK.Sprite.Framework;
using Dapper;
using Dapper.Contrib.Extensions;
using JetBrains.Annotations;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace CK.Sprite.Form.MySql
{
    public class SpriteObjectRepository : BaseSpriteRepository<SpriteObject>, ISpriteObjectRepository
    {
        public SpriteObjectRepository(IUnitOfWork unitOfWork) : base(unitOfWork) { }

        #region Sql

        private const string SqlGetAllSpriteObjectByApplicationCode = @"SELECT * FROM SpriteObjects WHERE ApplicationCode=@ApplicationCode;";

        #endregion

        public List<SpriteObject> GetAllSpriteObjectByApplicationCode(string applicationCode)
        {
            return _unitOfWork.Connection.Query<SpriteObject>(SqlGetAllSpriteObjectByApplicationCode, new { ApplicationCode = applicationCode }, _unitOfWork.Transaction).ToList();
        }

        public async Task ChangeObjectProperty(Guid objectId)
        {
            var strSql = $"SELECT * FROM ObjectPropertys WHERE ObjectId=@ObjectId;";
            var objectPropertys = (await _unitOfWork.Connection.QueryAsync<ObjectProperty>(strSql, new { ObjectId = objectId }, _unitOfWork.Transaction)).ToList();
            var strUpdateSql = $"UPDATE SpriteObjects SET PropertyJsons=@UpdateValue,Version=@Version WHERE Id=@ObjectId";
            string updateValue = "";
            if (objectPropertys.Count > 0)
            {
                updateValue = JsonConvert.SerializeObject(objectPropertys, new JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() });
            }
            await _unitOfWork.Connection.ExecuteAsync(strUpdateSql, new { ObjectId = objectId, UpdateValue = updateValue, Version = Guid.NewGuid() }, _unitOfWork.Transaction);
        }
    }
}
